<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="" prop="sampleTalentInfoId">
        <el-input v-model="queryParams.sampleTalentInfoId" placeholder="请输入达人信息表ID" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="templateId">
        <el-input v-model="queryParams.templateId" placeholder="请输入模板id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->

      <el-form-item label="" prop="liveDateStart">
        <el-date-picker clearable v-model="queryParams.liveDateStart" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择开始日期">
        </el-date-picker>
      </el-form-item>
      -
      <el-form-item label="" prop="liveDateEnd">
        <el-date-picker clearable v-model="queryParams.liveDateEnd" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="" prop="priceStart">
        <el-input v-model="queryParams.priceStart" placeholder="请输入最低价" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      -
      <el-form-item label="" prop="priceEnd">
        <el-input v-model="queryParams.priceEnd" placeholder="请输入最高价" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="mechanism">
        <el-input v-model="queryParams.mechanism" placeholder="请输入机制" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="pitLocationFeeStart">
        <el-input v-model="queryParams.pitLocationFeeStart" placeholder="请输入最低坑位费" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      -
      <el-form-item label="" prop="pitLocationFeeEnd">
        <el-input v-model="queryParams.pitLocationFeeEnd" placeholder="请输入最高坑位费" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="commission">
        <el-input v-model="queryParams.commission" placeholder="请输入佣金" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="" prop="salesQuantityStart">
        <el-input v-model="queryParams.salesQuantityStart" placeholder="请输入最低销售件数" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      -
      <el-form-item label="" prop="salesQuantityEnd">
        <el-input v-model="queryParams.salesQuantityEnd" placeholder="请输入最高销售件数" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="liveGmvStart">
        <el-input v-model="queryParams.liveGmvStart" placeholder="请输入最低GMV" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      -
      <el-form-item label="" prop="liveGmvEnd">
        <el-input v-model="queryParams.liveGmvEnd" placeholder="请输入最高GMV" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="liveRoiStart">
        <el-input v-model="queryParams.liveRoiStart" placeholder="请输入最低ROI" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      -
      <el-form-item label="" prop="liveRoiEnd">
        <el-input v-model="queryParams.liveRoiEnd" placeholder="请输入最高ROI" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="isSettlement">
        <el-input v-model="queryParams.isSettlement" placeholder="请输入是否结算" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="progress">
        <el-input v-model="queryParams.progress" placeholder="请输入进度" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="逻辑删除;0=未删除；1=已删除" prop="isDelete">
        <el-input v-model="queryParams.isDelete" placeholder="请输入逻辑删除;0=未删除；1=已删除" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:live:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:live:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:live:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:live:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-edit" size="mini" @click="openContact">寄样申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-edit" size="mini" @click="openPayApply">申请资金</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="tableDom">
      <el-table v-loading="loading" :maxHeight="liveList.length ? tableHeight : 'auto'" :data="liveList"
        @selection-change="handleSelectionChange" @row-dblclick="t">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="直播ID" align="center" prop="id" />
        <!--<el-table-column label="达人信息表ID" align="center" prop="sampleTalentInfoId" />
      <el-table-column label="模板id" align="center" prop="templateId" /> -->
        <el-table-column label="日期" align="center" prop="liveDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.liveDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="进度" align="center" prop="progress" />
        <el-table-column label="合作达人" align="center" prop="xhsNickname" width="130" />
        <el-table-column label="产品款式" align="center" prop="productNo" width="110px" />
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="机制" align="center" prop="mechanism" />
        <el-table-column label="坑位费" align="center" prop="pitLocationFee" />
        <el-table-column label="佣金" align="center" prop="commission" />
        <el-table-column label="销售件数" align="center" prop="salesQuantity" />
        <el-table-column label="GMV" align="center" prop="liveGmv" />
        <el-table-column label="ROI" align="center" prop="liveRoi" />
        <el-table-column label="是否结算" align="center" prop="isSettlement" />
        <!-- <el-table-column label="逻辑删除;0=未删除；1=已删除" align="center" prop="isDelete" /> -->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['product:live:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['product:live:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改样衣直播合作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <div class="el-dialog-div">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-col :span="8">
            <!-- <el-form-item label="达人信息表ID" prop="sampleTalentInfoId">
              <el-input v-model="form.sampleTalentInfoId" placeholder="请输入达人信息表ID" />
            </el-form-item>
            <el-form-item label="模板id" prop="templateId">
              <el-input v-model="form.templateId" placeholder="请输入模板id" />
            </el-form-item> -->
            <el-form-item label="日期" prop="liveDate">
              <el-date-picker clearable v-model="form.liveDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="进度" prop="progress">
              <el-input v-model="form.progress" placeholder="请输入进度" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
            <el-form-item label="机制" prop="mechanism">
              <el-input v-model="form.mechanism" placeholder="请输入机制" />
            </el-form-item>
            <el-form-item label="坑位费" prop="pitLocationFee">
              <el-input v-model="form.pitLocationFee" placeholder="请输入坑位费" />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item></el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="佣金" prop="commission">
              <el-input v-model="form.commission" placeholder="请输入佣金" />
            </el-form-item>
            <el-form-item label="销售件数" prop="salesQuantity">
              <el-input v-model="form.salesQuantity" placeholder="请输入销售件数" />
            </el-form-item>
            <el-form-item label="GMV" prop="liveGmv">
              <el-input v-model="form.liveGmv" placeholder="请输入GMV" />
            </el-form-item>
            <el-form-item label="ROI" prop="liveRoi">
              <el-input v-model="form.liveRoi" placeholder="请输入ROI" />
            </el-form-item>
            <el-form-item label="是否结算" prop="isSettlement">
              <el-input v-model="form.isSettlement" placeholder="请输入是否结算" />
            </el-form-item>
            <!-- <el-form-item label="逻辑删除;0=未删除；1=已删除" prop="isDelete">
          <el-input v-model="form.isDelete" placeholder="请输入逻辑删除;0=未删除；1=已删除" />
        </el-form-item> -->
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item></el-form-item>
          </el-col>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 寄样申请 -->
    <el-dialog title="寄样申请" :visible.sync="openCon" width="500px" append-to-body v-if="openCon">
      <el-form ref="Contact" :model="Contact" :rules="rules" label-width="120px">
        <el-form-item label="请选择收件地址" prop="address">
          <el-select v-model="Contact.id" @change="changeContact">
            <el-option v-for="item in optionsContact" :key="item.id"
              :label="`${item.recipient},${item.phone},${item.receiverState}${item.receiverCity}${item.receiverDistrict}${item.address}`"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否归还" prop="isReturn">
          <!-- <el-input v-model="Contact.isReturn" placeholder="是否归还" /> -->
          <el-select v-model="Contact.isReturn" placeholder="请选择是否归还" clearable filterable>
            <el-option v-for="dict in dict.type.sys_one_zero" :key="dict.value" :label="dict.label" :value="dict.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司" prop="expressCompany">
          <!-- <el-input v-model="Contact.expressCompany" placeholder="快递公司" /> -->
          <el-select v-model="Contact.expressCompany" placeholder="请选择快递公司" clearable filterable>
            <el-option v-for="dict in dict.type.sys_sample_sf" :key="dict.value" :label="dict.label"
              :value="dict.label" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitContact">确 定</el-button>
        <el-button @click="cancelContact">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 资金申请 -->
    <el-dialog title="申请资金" :visible.sync="openPay" width="500px" append-to-body v-if="openPay">
      <el-form ref="Pay" :model="Pay" :rules="rules" label-width="120px">
        <el-form-item label="请选择支付方式" prop="address">
          <el-select v-model="Pay.id">
            <el-option v-for="item in optionsPay" :key="item.id" :label="item.payMethod" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPay">确 定</el-button>
        <el-button @click="cancelPay">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSamplePaymentApply, getSamplePaymentApply, delSamplePaymentApply, addSamplePaymentApply, updateSamplePaymentApply } from "@/api/sample/samplePaymentApply";
import { listPay, getPay, delPay, addPay, updatePay } from "@/api/sample/pay";
import { listContact, getContact, delContact, addContact, updateContact } from "@/api/sample/contact";
import { listSampleApply, getSampleApply, delSampleApply, addSampleApply, updateSampleApply, addApply } from "@/api/sample/sampleApply";
import { listLive, getLive, delLive, addLive, updateLive } from "@/api/sample/live";

export default {
  name: "Live",
  dicts: ['sys_one_zero', 'sys_sample_sf'],
  data() {
    return {
      tableHeight: '',
      //支付申请
      openPay: false,
      optionsPay: [],
      Pay: {},
      //寄样
      openCon: false,
      optionsContact: [],
      Contact: {
        isReturn: '是',
        expressCompany: '中通快递'
      },
      //选中get
      sample: [],
      list: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 样衣直播合作表格数据
      liveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sampleTalentInfoId: null,
        templateId: null,
        liveDate: null,
        progress: null,
        price: null,
        mechanism: null,
        pitLocationFee: null,
        commission: null,
        salesQuantity: null,
        liveGmv: null,
        liveRoi: null,
        isSettlement: null,
        isDelete: null,
        liveDateStart: null,
        liveDateEnd: null,
        priceStart: null,
        priceEnd: null,
        pitLocationFeeStart: null,
        pitLocationFeeEnd: null,
        salesQuantityStart: null,
        salesQuantityEnd: null,
        liveGmvStart: null,
        liveGmvEnd: null,
        liveRoiStart: null,
        liveRoiEnd: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sampleTalentInfoId: [
          { required: true, message: "达人信息表ID不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "收货地址不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    var _this = this
    this.resizeTable()
    window.onresize = function () {
      _this.resizeTable()
    }
  },
  //记得清空  如果在keepalive中 则使用activated  deactivated
  destroyed() {
    window.onresize = null
  },
  methods: {
    //点击某一行
    t(row, column, cell, event) {
      console.log(row, column, cell, event);
      this.handleUpdate(row)
    },
    openPayApply() {
      if (this.sample.length > 1 || this.sample.length == 0) {
        this.$modal.msgError("请选择一个达人！");
        return
      }
      listPay({ sampleTalentInfoId: this.sample[0] }).then(res => {
        if (res.rows.length == 0) {
          this.$modal.msgError("请添加达人支付信息！");
          return


        } else if (res.rows.length > 0) {
          this.optionsPay = res.rows
          console.log(JSON.stringify(this.optionsPay));
          this.openPay = true
        }
      })

    },
    cancelPay() {
      this.openPay = false
    },

    submitPay() {
      if (!this.Pay.id) {
        this.$modal.msgError("请选择达人支付方式！");
        return
      }

      // return
      console.log(JSON.stringify(this.list));
      // for (var item in this.list) {
      //   if (item == 'sampleTalentTemplateList') {
      //     delete this.list[item];
      //   }
      // }
      var note = {}
      // // this.list.map(info => info.sampleTalentTemplateList)
      for (let i = 0; i < this.list.length; i++) {
        //   var info = this.list[i]
        //   // console.log(JSON.stringify(info.sampleTalentTemplateList));
        //   // note = this.list.map(info => info.sampleTalentTemplateList)
        //   // note.push(info.sampleTalentTemplateList)
        //   for (let j = 0; j < info.sampleTalentTemplateList.length; j++) {
        //     // const element = array[j];
        // note.assign({ sampleTalentInfoId: this.list[i].sampleTalentInfoId, sampleTalentPayId: this.Pay.id })
        // note[sampleTalentInfoId] = this.list[i].sampleTalentInfoId
        // note[sampleTalentPayId] = this.Pay.id
        note = { businessId: this.list[i].id, sampleTalentInfoId: this.sample[0], sampleTalentPayId: this.Pay.id, businessType: 'live' }
      }

      // }
      // if (note.length == 0) {
      //   this.$modal.msgError("请选择合作款式！");
      //   return
      // }

      console.log(JSON.stringify(note));
      // return

      addSamplePaymentApply(note).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess('申请成功')
          this.$router.push({ path: '/sample/samplePaymentApply', query: { id: this.sample[0] } })
          // this.getList()
        }
      })

    },
    openContact() {
      if (this.sample.length > 1 || this.sample.length == 0) {
        this.$modal.msgError("请选择一个达人！");
        return
      }
      listContact({ sampleTalentInfoId: this.sample[0] }).then(res => {
        if (res.rows.length == 0) {
          this.$modal.msgError("请添加达人收件信息！");
          return


        } else if (res.rows.length > 0) {
          this.optionsContact = res.rows
          console.log(JSON.stringify(this.optionsContact));
          this.openCon = true
        }
      })

    },
    cancelContact() {
      this.openCon = false
    },
    changeContact(val) {
      console.log(val);
      console.log(this.Contact.id);
    },

    submitContact() {

      if (!this.Contact.id) {
        this.$modal.msgError("请选择达人收件地址！");
        return
      }
      console.log(JSON.stringify(this.list));
      var live = []
      this.list.forEach(item => {
        live.push({ ...item, sampleTalentCooperateId: item.id, sampleTalentCooperateType: "live", contactId: this.Contact.id, isReturn: this.Contact.isReturn, expressCompany: this.Contact.expressCompany })
      })
      if (this.list.length == 0) {
        this.$modal.msgError("请选择合作款式！");
        return
      }
      console.log(JSON.stringify(live));
      // return
      addApply(live).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess('申请成功')
          this.$router.push({ path: '/sample/sampleApply', query: { id: this.sample[0] } })
          // this.getList()
        }
      })
    },
    /** 查询样衣直播合作列表 */
    getList() {
      this.loading = true;
      listLive(this.queryParams).then(response => {
        this.liveList = response.rows;
        console.log(JSON.stringify(this.liveList));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sampleTalentInfoId: null,
        templateId: null,
        liveDate: null,
        progress: null,
        price: null,
        mechanism: null,
        pitLocationFee: null,
        commission: null,
        salesQuantity: null,
        liveGmv: null,
        liveRoi: null,
        isSettlement: null,
        isDelete: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.list = selection.map(item => item)
      console.log(JSON.stringify(this.list));
      this.single = selection.length !== 1
      this.multiple = !selection.length
      var sampleTalentInfoId = selection.map(item => item.sampleTalentInfoId)
      console.log(JSON.stringify(Array.from(new Set(sampleTalentInfoId))));
      this.sample = Array.from(new Set(sampleTalentInfoId))
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加样衣直播合作";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLive(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改样衣直播合作";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLive(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLive(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除样衣直播合作编号为"' + ids + '"的数据项？').then(function () {
        return delLive(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/live/export', {
        ...this.queryParams
      }, `live_${new Date().getTime()}.xlsx`)
    },
    // table自动高度
    returnTableHeight(ref, bottomOffset) {
      let height = null
      height = window.innerHeight - ref.getBoundingClientRect().top - bottomOffset
      return height
    },


    resizeTable() {
      this.$nextTick(() => {
        this.tableHeight = this.returnTableHeight(this.$refs.tableDom, 100)
      }, 0)
    },
  }
};
</script>
<style lang="scss" scoped>
.el-dialog-div {
  height: 60vh;
  overflow-x: hidden;
}
</style>